import sys
import os
import re
import you_get
from utils import red_config
from threading import Thread

# 视频输出的目录
file_dir = red_config("$..you_get.path")
# 起始页码
start_page = red_config("$..you_get.start_page")
# 结束页面
end_page = red_config("$..you_get.end_page")
# 下载部分地址（不包含页码部分）
down_url_part = red_config("$..you_get.down_url")


def download(i):
    # 视频下载地址
    url = down_url_part + str(i)
    sys.argv = ['you-get', '-o', file_dir, url]
    you_get.main()


def rename():
    for old_name in os.listdir(file_dir):
        # old_name = "APPScan实战教程 (P1. 第一课 APPScan简介及安装).mp4"
        try:
            # 文件格式
            fmt = os.path.splitext(old_name)[1]
            # 文件新名
            new_name = re.search(r"\((.*?)\)", old_name).group(1) + fmt
            os.rename(file_dir + os.sep + old_name, file_dir + os.sep + new_name)
        except Exception as e:
            print(e)


def main():
    print(f"开始下载第{start_page}集到第{end_page}集视频")
    list_t = list()
    for i in range(start_page, end_page + 1):
        t = Thread(target=download, args=(i,))
        list_t.append(t)
        t.start()
    for t in list_t:
        t.join()
    print("重命名文件")
    rename()


if __name__ == '__main__':
    main()
